package com.summer.genericDynamicFactory;

import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;


class Platform {
    private static final Platform PLATFORM = findPlatform();

    static Platform get() {
        return PLATFORM;
    }

    private static Platform findPlatform() {
        switch (System.getProperty("java.vm.name")) {
            case "RoboVM":
                return new Platform(false);
            default:
                return new Platform(true);
        }
    }

    private final boolean hasJava8Types;
    private final Constructor<Lookup> lookupConstructor;

    Platform(boolean hasJava8Types) {

        this.hasJava8Types = hasJava8Types;
		Constructor<Lookup> lookupConstructor = null;

        this.lookupConstructor = lookupConstructor;
    }

    boolean isDefaultMethod(Method method) {
        return hasJava8Types && method.isDefault();
    }

    Object invokeDefaultMethod(Method method, Class<?> declaringClass, Object object, Object... args)
            throws Throwable {
        Lookup lookup = lookupConstructor != null ? lookupConstructor.newInstance(declaringClass, -1 /* trusted */)
                        : MethodHandles.lookup();
        return lookup.unreflectSpecial(method, declaringClass).bindTo(object).invokeWithArguments(args);
    }

}